# coding: utf-8
from typing import Union, List

from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout
from qeventmanager import qevent_manager
from qfluentwidgets import FlowLayout, FluentIcon as FIF, BodyLabel, IconWidget, PushButton

from common import signalBus
from common.server import BananaServer, TableSearchHistory
from components import GridLayout, ToolTipButton, CustomScrollArea, VideoCard, Alert


class TagWidget(QWidget):
    clearClickedSignal = Signal()

    def __init__(self, icon: Union[str, FIF, QIcon], title: str, parent=None):
        super().__init__(parent)
        self.iconWidget = IconWidget(icon, self)
        self.titleLabel = BodyLabel(title, self)
        self.clearBtn = ToolTipButton.transparentToolButton(self, FIF.BROOM, '清空')

        self.verticalLayout = QVBoxLayout(self)
        self.horizontalLayout = QHBoxLayout()
        self.flowLayout = FlowLayout()

        self.iconWidget.setFixedSize(16, 16)
        self.titleLabel.setFixedHeight(20)
        self.titleLabel.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)

        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)

        self.horizontalLayout.addWidget(self.iconWidget, 0, Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignLeft)
        self.horizontalLayout.addStretch(1)
        self.horizontalLayout.addWidget(self.clearBtn, 0, Qt.AlignmentFlag.AlignRight)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.verticalLayout.addLayout(self.flowLayout)

        self.clearBtn.clicked.connect(self.clearClickedSignal)
        self.clearBtn.setVisible(False)

    def clear(self):
        self.flowLayout.takeAllWidgets()
        self.updateGeometry()

    def addWidget(self, widget: QWidget):
        self.flowLayout.addWidget(widget)

    def addTag(self, tag: str):
        btn = PushButton(tag, self)
        btn.clicked.connect(lambda: signalBus.searchChanged.emit(tag))
        self.addWidget(btn)

    def setClearBtnVisible(self, visible: bool):
        self.clearBtn.setVisible(visible)


class SearchHistoryInterface(CustomScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.view = QWidget(self)
        self.verticalLayout = QVBoxLayout(self.view)
        self.historyWidget = TagWidget(FIF.HISTORY, '搜索历史', self.view)
        self.hotWidget = TagWidget(FIF.CALORIES, '热搜词', self.view)
        self.likeWidget = TagWidget(FIF.HEART, '猜你喜欢', self.view)

        self.gridLayout = GridLayout()

        self.__initWidgets()

        self.loadHistoryTag()

    def __initWidgets(self):
        self.setWidget(self.view)
        self.historyWidget.setClearBtnVisible(True)

        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(20)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)

        self.verticalLayout.addWidget(self.historyWidget)
        self.verticalLayout.addWidget(self.hotWidget)
        self.verticalLayout.addWidget(self.likeWidget)
        self.verticalLayout.addLayout(self.gridLayout)

        self.historyWidget.clearClickedSignal.connect(self.onClearHistory)
        signalBus.updateHistoryTagSig.connect(self.loadHistoryTag)

    def onClearHistory(self):
        self.historyWidget.clear()
        # qevent_manager.addSqlTaskToPool(clear_search_history)

    def addDataCard(self, data: dict):
        card = VideoCard(self)
        card.setData(data)
        self.gridLayout.addWidget(card)

    def load(self):
        qevent_manager.addTask(BananaServer.search_recommended, slot=self.onAddRecommendedData)

    def loadHistoryTag(self):
        self.historyWidget.clear()
        # qevent_manager.addSqlTaskToPool(get_search_history, slot=self.onAddHistoryData)

    def onAddRecommendedData(self, result: dict):
        if result['retcode'] != 0:
            Alert.error(result['message'])
            return
        data = result['data']
        hotwords = data.get('hotwords', [])
        hotrows = data.get('hotrows', [])
        you_may_likes = data.get('you_may_likes', [])
        if hotwords:
            for word in hotwords:
                self.hotWidget.addTag(word)
        for tag in you_may_likes:
            self.likeWidget.addTag(tag)
        for row in hotrows:
            if row['isvip'] != '0':
                continue
            card = VideoCard(self)
            card.setData(row)
            self.gridLayout.addWidget(card)

    def onAddHistoryData(self, result: List[TableSearchHistory]):
        self.historyWidget.clear()
        for row in result:
            self.historyWidget.addTag(row.key)
